package com.haois.mp.wechat.server;

import com.google.gson.internal.LinkedTreeMap;
import com.haois.mp.database.module.basic.util.SpringContextHolder;
import com.haois.mp.database.commom.enums.MpTypeEnum;
import com.haois.mp.database.module.common.daomain.UserToken;
import com.haois.mp.database.module.remote.service.IUserService;
import com.haois.mp.database.module.common.service.IUserTokenService;
import com.haois.mp.wechat.constants.Enum.MenuEnum;
import com.haois.mp.wechat.constants.UrlConstants;
import com.haois.mp.wechat.util.WxUtil;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * description
 *
 * @author RuiHaoZ on Hgits.cn
 * @date 2018/8/5 15:38
 */
@Component("QuickSearchServer")
public class QuickSearchServerImpl extends AbstractMoreInfoServer {

    @Autowired
    protected IUserService iUserService;
    @Autowired
    protected IUserTokenService iUserTokenService;
    @Value("${defined.wxmp.base-url}")
    private String baseUrl;

    @Override
    public String execute(WxMpXmlMessage wxMpXmlMessage) {
        WxMpService wxMpService = SpringContextHolder.getBean(WxMpService.class);
        UserToken userToken = iUserTokenService.findByOpenId(wxMpXmlMessage.getFromUser(), MpTypeEnum.OFFACCOUNTS.getType());
        String key = wxMpXmlMessage.getContent();
        String content = "";
        Map result = iUserService.getUserByName(userToken.getAccessToken(), key);
        if (("00").equals(result.get("code"))) {
            List<LinkedTreeMap> list = (List) result.get("data");

            int resultSize = list.size();
            boolean mul = resultSize > 1 ? true : false;
            for (int i = 0; i < resultSize; i++) {
                String url = UrlConstants.SHARE_MEMBER + "/" + list.get(i).get("memberNum");
                url = WxUtil.transferWxUrl(wxMpService, url, MenuEnum.BTN_SHARE_MEMBER.getKey(), baseUrl);
                content += "<a href=\"" + url + "\">" + list.get(i).get("name");
                if (mul) {
                    content += "<" + list.get(i).get("memberNum") + ">";
                }
                content += "</a>";
                content += " ☞[ " + list.get(i).get("mobiles") + " ]";
                if (i != resultSize - 1) {
                    content += "\n";
                }
            }
        } else {
            String msg = (String) result.get("msg");
            content = msg;
        }
        return content;
    }
}
